import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';

// API基础URL - 通过代理访问
const API_BASE_URL = '';

// 错误响应类型定义
interface ErrorResponse {
  response?: {
    status?: number;
    data?: {
      message?: string;
    };
  };
}

// 扩展AxiosRequestConfig以支持重试标记
interface ExtendedAxiosRequestConfig extends AxiosRequestConfig {
  _retry?: boolean;
  _refreshing?: boolean;
}

// 刷新Token响应类型
interface RefreshTokenResponse {
  code: number;
  message: string;
  data: {
    token: string;
    refreshToken: string;
  };
}

// 创建axios实例
const baseApi = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 定义错误信息映射
export const errorMessages: Record<number, string> = {
  400: '请求参数错误',
  401: '未授权，请重新登录',
  403: '拒绝访问',
  404: '请求资源不存在',
  500: '服务器内部错误',
  502: '网关错误',
  503: '服务不可用',
  504: '网关超时'
};

// 获取格式化的错误消息
export const getFormattedErrorMessage = (error: unknown): string => {
  const errorObj = error as ErrorResponse;
  const status = errorObj?.response?.status;
  const customMessage = errorObj?.response?.data?.message;
  
  // 获取错误消息: 自定义错误消息 > HTTP状态码对应消息 > 默认错误消息
  return customMessage || (status ? errorMessages[status] : null) || '服务器异常，请稍后再试';
};

// 正在刷新Token的Promise，防止并发刷新
let refreshTokenPromise: Promise<string | null> | null = null;

// 刷新Token函数
const refreshToken = async (): Promise<string | null> => {
  const refreshTokenValue = localStorage.getItem('refreshToken');
  if (!refreshTokenValue) {
    console.log('refreshTokenValue is null');
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
    window.location.href = '/login?expired=true';
    return null;
  }

  try {
    // 创建新的axios实例，避免拦截器循环调用
    const refreshApi = axios.create({
      baseURL: API_BASE_URL,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    const response = await refreshApi.post<RefreshTokenResponse>('/admin/token/refresh', {
      refreshToken: refreshTokenValue
    });

    if (response.data.code === 0 && response.data.data) {
      const { token, refreshToken: newRefreshToken } = response.data.data;
      
      // 更新本地存储
      localStorage.setItem('token', token);
      localStorage.setItem('refreshToken', newRefreshToken);
      
      return token;
    } else {
      throw new Error(response.data.message || '刷新Token失败');
    }
  } catch (error) {
    console.error('刷新Token失败:', error);
    
    // 清除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
    
    // 跳转到登录页
    if (window.location.pathname !== '/login') {
      window.location.href = '/login?expired=true';
    }
    
    return null;
  }
};

// 请求拦截器
baseApi.interceptors.request.use(
  (config) => {
    // 添加token到请求头
    const token = localStorage.getItem('token');
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
baseApi.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config as ExtendedAxiosRequestConfig;
    
    // 处理401错误（token过期）
    console.log(error,error.response?.status, originalRequest._retry);
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      
      // 如果已经在刷新Token，等待刷新完成
      if (refreshTokenPromise) {
        try {
          const newToken = await refreshTokenPromise;
          if (newToken && originalRequest.headers) {
            originalRequest.headers.Authorization = `Bearer ${newToken}`;
            return baseApi(originalRequest);
          }
        } catch (refreshError) {
          return Promise.reject(refreshError);
        }
      } else {
        // 开始刷新Token
        refreshTokenPromise = refreshToken();
        
        try {
          const newToken = await refreshTokenPromise;
          if (newToken && originalRequest.headers) {
            originalRequest.headers.Authorization = `Bearer ${newToken}`;
            return baseApi(originalRequest);
          } else {
            return Promise.reject(new Error('会话已过期，请重新登录'));
          }
        } catch (refreshError) {
          return Promise.reject(refreshError);
        } finally {
          // 重置刷新Promise
          refreshTokenPromise = null;
        }
      }
    }
    
    // 其他错误直接返回
    return Promise.reject(error);
  }
);

export default baseApi; 